package com.example.demojenkins.domain;

import com.alibaba.fastjson2.annotation.JSONField;
import com.example.demojenkins.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @author: LZ
 * @description:
 * @since 2024-08-19 18:04
 */
public class LoginUser implements UserDetails {

    //存放用户信息
    private User user;

    //存放权限信息
    private List<String> permissions;

    //这个属性不需要被序列化，他只是为getAuthorities()方法做转型使用
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }

    public LoginUser() {
    }

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /**
     * 框架并不会主动调用我们自己定义的集合permissions来获取用户的权限信息，
     * 只能从重写的方法getAuthorities（）获取，把自定义的集合转化成方法所需要的类型
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null){
            return authorities;
        }
        authorities = permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
